package com.example.personalcenter; // 请替换成你自己的包名

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    // 定义消息代码
    private static final int LOGIN_SUCCESS = 1;
    private static final int LOGIN_FAILED = 0;
    private static final int LOGIN_START = 2;

    // 控件定义
    private EditText editTextUsername;
    private EditText editTextPassword;
    private CheckBox checkboxAgreement;
    private Button buttonLogin;
    private TextView tvRegister;
    private ProgressBar progressBar;
    private ImageView ivPasswordToggle;

    // 扩展功能：标记密码是否可见
    private boolean isPasswordVisible = false;


    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_START:
                    progressBar.setVisibility(View.VISIBLE);
                    buttonLogin.setEnabled(false);
                    Toast.makeText(MainActivity.this, "登录中...", Toast.LENGTH_SHORT).show();
                    break;
                case LOGIN_SUCCESS:
                    progressBar.setVisibility(View.GONE);
                    buttonLogin.setEnabled(true);
                    // 要求3. (3): 登录成功提示
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    break;
                case LOGIN_FAILED:
                    progressBar.setVisibility(View.GONE);
                    // 登录失败后，需要重新判断复选框状态来决定按钮是否可用
                    buttonLogin.setEnabled(checkboxAgreement.isChecked());
                    Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cons);

        // 初始化所有控件
        initViews();

        // 设置监听器
        setupListeners();
    }

    private void initViews() {
        editTextUsername = findViewById(R.id.editText_username);
        editTextPassword = findViewById(R.id.editText_password);
        checkboxAgreement = findViewById(R.id.checkbox_agreement);
        buttonLogin = findViewById(R.id.button_login);
        tvRegister = findViewById(R.id.tv_register);
        progressBar = findViewById(R.id.progressBar);
        ivPasswordToggle = findViewById(R.id.iv_password_toggle);
    }

    private void setupListeners() {
        // 要求1.2: 用户名输入框失去焦点时，自动去掉前后空格
        editTextUsername.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String trimmedUsername = editTextUsername.getText().toString().trim();
                    editTextUsername.setText(trimmedUsername);
                }
            }
        });

        // 要求二、协议勾选框交互
        checkboxAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 根据是否勾选，设置登录按钮是否可用（变亮/变灰）
                buttonLogin.setEnabled(isChecked);
            }
        });

        // 要求三、登录按钮点击事件
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取输入内容并去除前后空格
                final String username = editTextUsername.getText().toString().trim();
                final String password = editTextPassword.getText().toString().trim();

                // 要求3. (1): 检查用户名和密码是否为空
                if (username.isEmpty()) {
                    Toast.makeText(MainActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
                    return; // 终止执行
                }
                if (password.isEmpty()) {
                    Toast.makeText(MainActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return; // 终止执行
                }

                // 要求3. (2): 检查协议是否勾选 (虽然按钮已禁用，但双重保险)
                if (!checkboxAgreement.isChecked()) {
                    Toast.makeText(MainActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                    return; // 终止执行
                }

                // 所有检查通过，开始执行登录逻辑（你原有的子线程逻辑）
                startLoginThread(username, password);
            }
        });

        // 要求四、注册提示文字点击事件
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "跳转到注册页", Toast.LENGTH_SHORT).show();
            }
        });

        // 扩展部分: “显示/隐藏密码” 功能
        ivPasswordToggle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPasswordVisible = !isPasswordVisible; // 切换状态
                if (isPasswordVisible) {
                    // 显示密码
                    editTextPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ivPasswordToggle.setImageResource(R.drawable.ic_eye_visible); // 更换为“睁眼”图标
                } else {
                    // 隐藏密码
                    editTextPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ivPasswordToggle.setImageResource(R.drawable.ic_eye_hidden); // 更换为“闭眼”图标
                }
                // 重要：每次切换类型后，需要将光标移到文本末尾
                editTextPassword.setSelection(editTextPassword.getText().length());
            }
        });
    }

    private void startLoginThread(final String username, final String password) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                handler.sendEmptyMessage(LOGIN_START);

                try {
                    Thread.sleep(2000); // 模拟网络延时
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if ("admin".equals(username) && "123456".equals(password)) {
                    handler.sendEmptyMessage(LOGIN_SUCCESS);
                } else {
                    handler.sendEmptyMessage(LOGIN_FAILED);
                }
            }
        }).start();
    }
}